﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace Maintenance.Util
{
    /// <summary>
    /// 更换壁纸
    /// </summary>
    public class WallpaperHelper
    {
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        /// <summary>
        /// 更换壁纸
        /// </summary>
        /// <param name="fileName">壁纸文件的路径</param>
        /// <returns>操作结果：true为更换成功，false为更换失败</returns>
        public static bool ChangeWallPaper(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }
            if (File.Exists(fileName) == false)
            {
                return false;
            }

            fileName = Path.GetFullPath(fileName);
            var nResult = SystemParametersInfo(20, 1, fileName, 0x1 | 0x2); //更换壁纸
            if (nResult == 0)
            {
                return false;
            }
            else
            {
                RegistryKey hk = Registry.CurrentUser;
                RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
                run.SetValue("Wallpaper", fileName);

                return true;
            }
        }
    }
}